package com.chaos.framework.starter.config.feign;

import cn.hutool.core.util.ObjectUtil;
import com.chaos.framework.model.constant.Constants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
public class OpenFeignRequestInterceptor implements RequestInterceptor {
    private static final String HEADER_USER_ID = "X-User-Id";
    private static final String HEADER_USER_INFO_ID = "X-User-Info-Id";
    private static final String HEADER_TENANT_ID = "X-Tenant-Id";

    @Override
    public void apply(RequestTemplate requestTemplate) {

        String traceId = MDC.get(Constants.TRACE_ID);
        requestTemplate.header(Constants.TRACE_ID, traceId);
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attr = (ServletRequestAttributes) requestAttributes;
        if (ObjectUtil.isNull(attr)) {
            return;
        }
        HttpServletRequest request = attr.getRequest();
        String userId = request.getHeader(HEADER_USER_ID);
        if (StringUtils.hasText(userId)) {
            requestTemplate.header(HEADER_USER_ID, userId);
        }
        String userInfoId = request.getHeader(HEADER_USER_INFO_ID);
        if (StringUtils.hasText(userInfoId)) {
            requestTemplate.header(HEADER_USER_INFO_ID, userInfoId);
        }
        String tenantId = request.getHeader(HEADER_TENANT_ID);
        if (StringUtils.hasText(userId)) {
            requestTemplate.header(HEADER_TENANT_ID, tenantId);
        }

    }


}